package com.ylaihui.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("receive file form client.");
        // 多段的数据无法通过 name 属性的值获取 数据 ---- multipart/form-data
        //System.out.println(req.getParameter("username"));
        //System.out.println(req.getParameter("tupian"));

        // 1. 判断是否为多段数据
        if (ServletFileUpload.isMultipartContent(req)) {
            System.out.println("receive multipart data form client.");

            // 2.1创建 FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //2. 创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

            //3. 解析上传的数据，得到每一个表单项FileItem
            try {
                List<FileItem> list = fileUpload.parseRequest(req);
                for (FileItem fileItem : list) {
                    if(fileItem.isFormField()) {
                        // 普通的表单项
                        System.out.println(fileItem.getFieldName());
                        System.out.println(fileItem.getString("UTF-8"));
                    }else {
                        // 上传的文件
                        System.out.println(fileItem.getFieldName());
                        System.out.println(fileItem.getName());
                        //写文件到某个目录下
                        //try {
                        //    fileItem.write(new File("/Users/lisimmy/_Temp/" + fileItem.getName() ));
                        //} catch (Exception e) {
                        //    e.printStackTrace();
                        //}
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }
    }
}
